package cn.t222.ch04.ex;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/error")
@RestControllerAdvice
public class CustomErrorController implements ErrorController {
    BasicErrorController c;
    @RequestMapping
    public Map<String, Object> handleError(HttpServletRequest request) {
        //用Map容器返回信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", "404");
        map.put("msg", "不存在");
        return map;
    }
    @ExceptionHandler(value = {Exception.class})
    public Object handler1(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> error = new HashMap<>();
        error.put("msg", e.getMessage());
        error.put("date", new Date());
        error.put("code", "500");
        return error;
    }

    @Override
    public String getErrorPath() {
        return null;
    }
   /* //    BasicErrorController c;
    //4xx...
    @RequestMapping
    public Map<String, Object> handleError(HttpServletRequest request) {
        //用Map容器返回信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", getStatus(request).value());
        map.put("msg", "不存在");
        return map;
    }
    //5xx
    @ExceptionHandler(value = {Exception.class})
    public Object handler1(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> error = new HashMap<>();
        error.put("msg", e.getMessage());
        error.put("date", new Date());
        error.put("code", getStatus(request).value());
        return error;
    }

    @Override
    public String getErrorPath() {
        return null;
    }

    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }*/
}
